using ParadoxNotion.Design;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI.Utils;

namespace Yoozoo.Gameplay.Liberty.AI.Node
{
    [Category("Ggame/Liberty")]
    public class SetNpc2NearPathPoint : AIBaseNode
    {
        protected override void OnExecute()
        {
            Vector3 pos = _transform.position;
            Vector3 forward = _transform.forward;
            _entity.seeker.SwitchSpeedStrategy(SpeedStrategyType.Const);
            float offsetFactor = _entity.data.pathOffsetFactor;

            PathPointData point = null;
            PathPointData closetPathPoint = LibertyAIUtils.TrafficManager.PathManager.GetClosestPathPoints(_entity.data.pathId, pos);
            if (closetPathPoint == null)
            {
                closetPathPoint = LibertyAIUtils.TrafficManager.PathManager.GetNearestPointByArea(pos, PathType.Npc);
            }
            _entity.data.pathId = closetPathPoint.pathId; 
            PathPointData nextPoint = LibertyAIUtils.TrafficManager.PathManager.GetNextPoint(_entity.data.pathId, closetPathPoint.pointIndex,
                _entity.data.pathDirection);

            Vector3 dirV = nextPoint.position - closetPathPoint.position;
            Vector3 v1 = closetPathPoint.position - pos;
            if (Vector3.Angle(dirV,v1) > 90)
            {
                point = nextPoint;
            }
            else
            {
                point = closetPathPoint;
            }
            
            //var point = LibertyAIUtils.TrafficManager.PathManager.GetNearestNavPoint(pos, forward, out PathDirection pathDirection);
            if (point!=null)
            {
                Vector3 destination = AIGraphUtils.GetNpcDestinationFormPoint(point, GetPosition(), offsetFactor);

                _entity.data.destination = destination;
                //_entity.data.pathDirection = pathDirection;
                _entity.data.pathId = point.pathId;
                _entity.data.pathPointIndex = point.pointIndex;
                SetDestination(destination);
            }
            else
            {
                EndAction(false);
            }
        }


        protected override void OnUpdate()
        {
            base.SetTransformData();
            if (_entity.seeker.ReachedEndOfPath())
            {
                EndAction(true);
            }
        }
    }
}